package com.ruoyi.web.controller.uav;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.uav.domain.UavTrainingPropose;
import com.ruoyi.uav.service.IUavTrainingProposeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 训练想定Controller
 *
 * @author ruoyi
 * @date 2024-01-04
 */
@RestController
@RequestMapping("/uav/propose")
@Api(value = "训练想定控制层", tags = "训练想定控制层")
public class UavTrainingProposeController extends BaseController {
    @Resource
    private IUavTrainingProposeService uavTrainingProposeService;

    /**
     * 查询训练想定列表
     */
    @PreAuthorize("@ss.hasPermi('uav:propose:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询训练想定列表", notes = "传入uavTrainingPropose")
    public TableDataInfo list(UavTrainingPropose uavTrainingPropose) {
        startPage();
        List<UavTrainingPropose> list = uavTrainingProposeService.selectUavTrainingProposeList(uavTrainingPropose);
        return getDataTable(list);
    }

    /**
     * 导出训练想定列表
     */
    @PreAuthorize("@ss.hasPermi('uav:propose:export')")
    @Log(title = "训练想定", businessType = BusinessType.EXPORT)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping("/export")
    @ApiOperation(value = "导出训练想定列表", notes = "传入uavTrainingPropose")
    public AjaxResult export(UavTrainingPropose uavTrainingPropose) {
        List<UavTrainingPropose> list = uavTrainingProposeService.selectUavTrainingProposeList(uavTrainingPropose);
        ExcelUtil<UavTrainingPropose> util = new ExcelUtil<>(UavTrainingPropose.class);
        return util.exportExcel(list, "训练想定数据");
    }

    /**
     * 获取训练想定详细信息
     */
    @PreAuthorize("@ss.hasPermi('uav:propose:query')")
    @GetMapping(value = "/{trainingProposeId}")
    @ApiOperation(value = "获取训练想定详细信息", notes = "传入trainingProposeId")
    public R<UavTrainingPropose> getInfo(@PathVariable("trainingProposeId") Long trainingProposeId) {
        return R.ok(uavTrainingProposeService.getById(trainingProposeId));
    }

    /**
     * 新增训练想定
     */
    @PreAuthorize("@ss.hasPermi('uav:propose:add')")
    @Log(title = "训练想定", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping
    @ApiOperation(value = "新增训练想定", notes = "传入uavTrainingPropose")
    public AjaxResult add(@RequestBody UavTrainingPropose uavTrainingPropose) {
        // 校验并设置想定名称
        String proposeName = uavTrainingPropose.getProposeName().trim();
        uavTrainingPropose.setProposeName(proposeName);

        ImmutablePair<Boolean, String> result = checkProposeName(proposeName, null);
        if (!result.getLeft()) {
            return error(result.getRight());
        }
        // 新增想定信息
        uavTrainingPropose.setCreateBy(SecurityUtils.getUsername());
        uavTrainingPropose.setCreateTime(DateUtils.getNowDate());
        return success(uavTrainingProposeService.getBaseMapper().insert(uavTrainingPropose));
    }

    /**
     * 修改训练想定
     */
    @PreAuthorize("@ss.hasPermi('uav:propose:edit')")
    @Log(title = "训练想定", businessType = BusinessType.UPDATE)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PutMapping
    @ApiOperation(value = "修改训练想定", notes = "传入uavTrainingPropose")
    public AjaxResult edit(@RequestBody UavTrainingPropose uavTrainingPropose) {
        // 校验并设置想定名称
        String proposeName = uavTrainingPropose.getProposeName().trim();
        uavTrainingPropose.setProposeName(proposeName);

        ImmutablePair<Boolean, String> result = checkProposeName(proposeName, uavTrainingPropose.getTrainingProposeId());
        if (!result.getLeft()) {
            return error(result.getRight());
        }
        // 更新想定信息
        uavTrainingPropose.setUpdateBy(SecurityUtils.getUsername());
        uavTrainingPropose.setUpdateTime(DateUtils.getNowDate());
        return success(uavTrainingProposeService.updateById(uavTrainingPropose));
    }

    /**
     * 删除训练想定
     */
    @PreAuthorize("@ss.hasPermi('uav:propose:remove')")
    @Log(title = "训练想定", businessType = BusinessType.DELETE)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
	@DeleteMapping("/{trainingProposeIds}")
    @ApiOperation(value = "删除训练想定", notes = "传入trainingProposeIds")
    public R<Integer> remove(@PathVariable Long[] trainingProposeIds) {
        return R.ok(uavTrainingProposeService.getBaseMapper().deleteBatchIds(Arrays.asList(trainingProposeIds)));
    }


    /**
     * 检查训练想定名称是否合法。
     *
     * @param proposeName 训练想定名称，需要进行检查的字符串。
     * @param id          要检查的训练想定的 ID，如果为 null，则表示新增操作，否则为修改操作。
     * @return 返回一个 ImmutablePair 对象，其中 left 表示检查结果（true 表示合法，false 表示不合法），right 表示错误信息（如果合法则为空字符串）。
     */
    private ImmutablePair<Boolean, String> checkProposeName(String proposeName, Long id) {
        // 检查训练想定名称是否为空
        if (StringUtils.isEmpty(proposeName)) {
            return new ImmutablePair<>(false, "想定名称不能为空");
        }
        // 查询数据库中是否存在相同的训练想定名称
        if (uavTrainingProposeService.count(Wrappers.<UavTrainingPropose>lambdaQuery()
                .eq(UavTrainingPropose::getProposeName, proposeName)
                .ne(ObjectUtils.isNotNull(id), UavTrainingPropose::getTrainingProposeId, id)) > 0) {
            return new ImmutablePair<>(false, "想定名称已存在");
        }
        return new ImmutablePair<>(true, "");
    }
}
